package co.baiku.boot.core.web.filter;

import co.baiku.boot.common.tools.StringTools;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 跨域配置
 */

@Component
@WebFilter(urlPatterns = "/*", filterName = "crossOrigin")
public class CrossOriginFilter implements Filter {

    private Logger log = LoggerFactory.getLogger(CrossOriginFilter.class);

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        log.debug("crossOrigin init");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        ((HttpServletResponse) response).setHeader("Access-Control-Allow-Origin", ((HttpServletRequest) request).getHeader("Origin"));
        ((HttpServletResponse) response).setHeader("Access-Control-Allow-Credentials", "true");
        ((HttpServletResponse) response).setHeader("Access-Control-Max-Age", "3600");
        ((HttpServletResponse) response).setHeader("Access-Control-Allow-Headers", "Origin,X-Requested-With,Content-Type,Accept,Authorization");
        ((HttpServletResponse) response).setHeader("Access-Control-Allow-Methods", "GET,POST,DELETE,PUT,OPTIONS");

        String scheme = request.getScheme();
        if (StringTools.isNotBlank(scheme) && "https".equalsIgnoreCase(scheme)) {
            ((HttpServletResponse) response).setHeader("Set-Cookie", "JSESSIONID=" + ((HttpServletRequest) request).getSession().getId() + "; Path=/cas;HttpOnly=true;Secure=true;");
            ((HttpServletResponse) response).setHeader("Strict-Transport-Security", "max-age=31536000; includeSubdomains; preload");
            ((HttpServletResponse) response).setHeader("X-Frame-Options", "SAMEORIGIN;");
            ((HttpServletResponse) response).setHeader("X-XSS-Protection", "\"1; mode=block\";");
        }

        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {

    }
}
